package api

import (
	"FeedXmh/app/dao"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

var User = user{}

type user struct{}

func (*user) GET(r *ghttp.Request) {
	params := r.GetQueryMap()
	userid := gconv.String(params["userid"])
	if userid == "" {
		claims := jwt.ExtractClaims(r)
		if claims == nil {
			r.Response.Write("error")
		} else {
			userid = gconv.String(claims["userid"])
		}
	}

	res := dao.T_user.GetUserInfo(userid)
	r.Response.Write(res.Json())
	r.ExitAll()
}

func (*user) Info(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	//params := r.GetQueryMap()
	//userid := gconv.String(params["userid"])
	claims := jwt.ExtractClaims(r)
	if claims == nil {
		res["code"] = -1
		res["msg"] = "error auth"
	} else {
		userid := gconv.String(claims["userid"])
		record := dao.T_user.GetUserInfo(userid)
		res["code"] = 0
		res["data"] = record
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) PUT(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}

	params := r.GetFormMap()
	id := gconv.Int(params["id"])
	userid := gconv.String(params["userid"])
	name := gconv.String(params["name"])
	email := gconv.String(params["email"])
	//phone := params["phone"]
	phone := userid
	//default_farm := gconv.Int(params["default_farm"])
	position_type := gconv.String(params["position_type"])
	role_id := gconv.String(params["role_id"])
	group_code := gconv.String(params["group_code"])
	area_ids := gconv.String(params["area_ids"])
	farmid_ids := gconv.String(params["farmid_ids"])
	/*var role_map = map[string]interface{}{}
	if params["role"] != nil {
		role_map = params["role"].(map[string]interface{})
	}*/
	//g.Dump(role_map)
	//create_time := gtime.Now().Format("Y-m-d H:i:s.u")
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, current_user) {
		if tx, err := db.Begin(); err == nil {

			user_item := gdb.Map{
				"id":            id,
				"userid":        userid,
				"name":          name,
				"email":         email,
				"phone":         phone,
				"position_type": position_type,
				"group_code":    group_code,
			}

			model := tx.Model("t_user")
			model = model.Data(user_item)
			model = model.Where(fmt.Sprintf("id='%d'", id))
			model.Update()
			_, err := model.Update()
			if err == nil {
				//清空该用户所有角色
				_, err = tx.Model("t_user_roles").Where("userid=?", userid).Delete()
			}
			if err == nil {
				//写入角色
				item := gdb.Map{"userid": userid, "role_id": role_id}
				_, err = tx.Model("t_user_roles").Data(item).Insert()
			}

			if err == nil {
				//清空area
				_, err = tx.Model("t_user_area").Where("userid=?", userid).Delete()
			}
			if err == nil {
				//写入area
				if area_ids != "" {
					var save_list gdb.List
					arr := gstr.Split(area_ids, ",")
					for _, v := range arr {
						item := gdb.Map{"userid": userid, "area_id": v, "create_date": gtime.Now().String(), "create_user": current_user}
						save_list = append(save_list, item)
					}

					if len(save_list) > 0 {
						_, err = tx.Model("t_user_area").Data(save_list).Insert()
					}
				}
			}

			if err == nil {
				//清空farm
				_, err = tx.Model("t_user_farm").Where("userid=?", userid).Delete()
			}
			if err == nil {
				//写入area
				if farmid_ids != "" {
					var save_list gdb.List
					arr := gstr.Split(farmid_ids, ",")
					for _, v := range arr {
						item := gdb.Map{"userid": userid, "farmid": v, "create_date": gtime.Now().String(), "create_user": current_user}
						save_list = append(save_list, item)
					}

					if len(save_list) > 0 {
						_, err = tx.Model("t_user_farm").Data(save_list).Insert()
					}
				}
			}

			if err == nil {
				tx.Commit()
				res["code"] = 0
				res["msg"] = "ok"
			} else {
				tx.Rollback()
				res["code"] = -1
				res["msg"] = err.Error()
			}
		}

	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) POST(r *ghttp.Request) {

	res := g.Map{
		"code": 0,
		"msg":  "",
	}

	params := r.GetFormMap()

	userid := gconv.String(params["userid"])
	name := gconv.String(params["name"])
	email := gconv.String(params["email"])
	//phone := params["phone"]
	phone := userid
	//default_farm := gconv.Int(params["default_farm"])
	position_type := gconv.String(params["position_type"])
	role_id := gconv.String(params["role_id"])
	group_code := gconv.String(params["group_code"])
	area_ids := gconv.String(params["area_ids"])
	farmid_ids := gconv.String(params["farmid_ids"])
	/*var role_map = map[string]interface{}{}
	if params["role"] != nil {
		role_map = params["role"].(map[string]interface{})
	}*/
	//g.Dump(role_map)

	create_time := gtime.Now()
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))

	count, _ := db.Model("t_user").Where(fmt.Sprintf("userid='%s'", userid)).Count()

	if dao.CheckApiPermission(url, r.Method, current_user) {
		if tx, err := db.Begin(); err == nil {
			//判断用户是否已经存在
			if count > 0 {
				res["code"] = -1
				res["msg"] = "用户已经存在"
			} else {

				//初始密码设置
				pwd := "123456"
				if len(userid) >= 6 {
					pwd = userid[len(userid)-6:]
				} else {

				}
				_, err := tx.Model("t_user").Data(
					gdb.Map{
						"userid":        userid,
						"pwd":           pwd,
						"name":          name,
						"email":         email,
						"phone":         phone,
						"position_type": position_type,
						"group_code":    group_code,
						"create_time":   create_time,
						"create_by":     current_user,
					}).Insert()
				if err == nil {
					//清空该用户所有角色
					_, err = tx.Model("t_user_roles").Where("userid=?", userid).Delete()
				}
				if err == nil {
					//写入角色
					item := gdb.Map{"userid": userid, "role_id": role_id}
					_, err = tx.Model("t_user_roles").Data(item).Insert()
				}

				if err == nil {
					//清空area
					_, err = tx.Model("t_user_area").Where("userid=?", userid).Delete()
				}
				if err == nil {
					//写入area
					if area_ids != "" {
						var save_list gdb.List
						arr := gstr.Split(area_ids, ",")
						for _, v := range arr {
							item := gdb.Map{"userid": userid, "area_id": v, "create_date": gtime.Now().String(), "create_user": current_user}
							save_list = append(save_list, item)
						}

						if len(save_list) > 0 {
							_, err = tx.Model("t_user_area").Data(save_list).Insert()
						}
					}
				}

				if err == nil {
					//清空farm
					_, err = tx.Model("t_user_farm").Where("userid=?", userid).Delete()
				}
				if err == nil {
					//写入area
					if farmid_ids != "" {
						var save_list gdb.List
						arr := gstr.Split(farmid_ids, ",")
						for _, v := range arr {
							item := gdb.Map{"userid": userid, "farmid": v, "create_date": gtime.Now().String(), "create_user": current_user}
							save_list = append(save_list, item)
						}

						if len(save_list) > 0 {
							_, err = tx.Model("t_user_farm").Data(save_list).Insert()
						}
					}
				}

				if err == nil {
					tx.Commit()
					res["code"] = 0
					res["msg"] = "ok"
				} else {
					tx.Rollback()
					res["code"] = -1
					res["msg"] = err.Error()
				}

			}
			if res["code"].(int) >= 0 {
				tx.Commit()
			} else {
				tx.Rollback()
			}
		}

	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) DELETE(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	id := r.GetFormMap()["id"]
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, current_user) {
		sqlres, _ := db.Model("t_user").Where("id=?", id).Delete()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) GetUsers(r *ghttp.Request) {

	params := r.GetQueryMap()

	where := ""
	role := gconv.String(params["role"])
	key := gconv.String(params["key"])
	if role != "" {
		where += " and FIND_IN_SET('" + role + "', role_ids) "
	}
	if key != "" {
		where += " and concat(userid,name) like '%" + key + "%' "
	}
	id := gconv.String(params["id"])
	if id != "" {
		where += " and id='" + id + "'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	if dao.CheckApiPermission(url, r.Method, userid) {
		res := dao.GetPermitUserList(userid, where)
		r.Response.WriteJson(g.Map{
			"code":  0,
			"msg":   "",
			"count": len(res),
			"data":  res,
		})
	} else {
		r.Response.WriteJson(g.Map{
			"code":  0,
			"msg":   "permission denied",
			"count": 0,
			"data":  nil,
		})
	}

	//r.Response.Write(res.Json())
	r.ExitAll()
}

func (*user) GetUserActions(r *ghttp.Request) {
	func_url := r.GetString("func_url")
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	var model = &gdb.Model{}
	if !dao.IsAdmin(userid) {
		model = db.Model("v_permission").Fields("DISTINCT action_id").Where("userid=? and func_url=? ", userid, func_url)
	} else {
		model = db.Model("t_action").Fields("id as action_id")
	}
	res, err := model.All()
	if err != nil {
		g.Log().Line().Error(err)
	}

	r.Response.WriteJson(g.Map{
		"code":  0,
		"msg":   "",
		"count": len(res),
		"data":  res.List(),
	})
	r.ExitAll()
}

// 获取用户具有权限的养殖场
func (*user) GetUserFarms(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	result := dao.GetPermisFarm(userid)
	res["data"] = result
	res["count"] = len(result)
	r.Response.WriteJson(res)
	r.ExitAll()
}

// 设置用户拓扑权限
func (*user) SetUserOrg(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()
	userid := gconv.String(params["userid"])
	farmids := gconv.String(params["farmids"])
	houseids := gconv.String(params["houseids"])

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if tx, err := db.Begin(); err == nil {
			_, err = tx.Model("t_user_farm").Where("userid=?", userid).Delete()
			if err == nil {
				if farmids != "" {
					var _list gdb.List
					_farmids := gstr.Split(farmids, ",")
					for _, farmid := range _farmids {
						_item := gdb.Map{
							"userid":      userid,
							"farmid":      farmid,
							"create_date": gtime.Now().String(),
							"create_user": current_user,
						}
						_list = append(_list, _item)
					}
					if len(_list) > 0 {
						_, err = tx.Model("t_user_farm").Data(_list).Save()
					}
				}

				_, err = tx.Model("t_user_house").Where("userid=?", userid).Delete()
				if err == nil {
					if houseids != "" {
						var _list gdb.List
						_houseids := gstr.Split(houseids, ",")
						for _, houseid := range _houseids {
							_item := gdb.Map{
								"userid":      userid,
								"houseid":     houseid,
								"create_date": gtime.Now().String(),
								"create_user": current_user,
							}
							_list = append(_list, _item)
						}
						if len(_list) > 0 {
							_, err = tx.Model("t_user_house").Data(_list).Save()
						}
					}
				}
			}

			if err != nil {
				tx.Rollback()
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				tx.Commit()
				res["code"] = 0
				res["msg"] = "保存成功"
			}

		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// 获取用户具有权限的设备
func (*user) GetUserDevices(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	result, err := dao.GetUserDevice(userid)
	if err != nil {
		g.Log().Line().Error(err)
		res["code"] = -1
		res["msg"] = err.Error()
	} else {
		res["data"] = result
		res["count"] = len(result)
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) GetUserPermission(r *ghttp.Request) {
	func_url := r.GetString("func_url")
	where := " 1=1 "
	if func_url != "" {
		where += fmt.Sprintf(" and func_url='%s' ", func_url)
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	var model = &gdb.Model{}
	if !dao.IsAdmin(userid) {
		model = db.Model("v_permission").Fields("DISTINCT distinct action_id,func_id,func_url").Where(where)
	} else {
		model = db.Model("v_permission_all").Fields("DISTINCT distinct action_id,func_id,func_url").Where(where)
	}
	res, err := model.All()
	if err != nil {
		g.Log().Line().Error(err)
	}

	r.Response.WriteJson(g.Map{
		"code":  0,
		"msg":   "",
		"count": len(res),
		"data":  res.List(),
	})
	r.ExitAll()
}

func (*user) Enable(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)

	params := r.GetFormMap()
	userid := gconv.String(params["userid"])
	status := 1
	//url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.IsAdmin(current_user) {
		sqlres, _ := db.Model("t_user").Data(gdb.Map{"status": status}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
func (*user) Disable(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	params := r.GetFormMap()
	userid := gconv.String(params["userid"])
	status := 0
	//url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.IsAdmin(current_user) {
		sqlres, _ := db.Model("t_user").Data(gdb.Map{"status": status}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) SetAdmin(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	params := r.GetFormMap()
	userid := gconv.String(params["userid"])
	admin := gconv.Int(params["is_admin"])
	//admin := r.GetInt("is_admin")
	//url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.IsAdmin(current_user) {
		sqlres, _ := db.Model("t_user").Data(gdb.Map{"admin": admin}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
func (*user) ResetPwd(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	params := r.GetFormMap()
	userid := gconv.String(params["userid"])
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, current_user) {
		pwd := "123456"
		if len(userid) >= 6 {
			pwd = userid[len(userid)-6:]
		} else {

		}
		sqlres, _ := db.Model("t_user").Data(gdb.Map{"pwd": pwd}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) EditProfile(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}

	params := r.GetFormMap()
	userid := params["userid"]
	name := params["name"]
	email := params["email"]
	phone := params["phone"]
	phone_notice := gconv.Int(params["phone_notice"])
	email_notice := gconv.Int(params["email_notice"])
	default_page := params["default_page"]

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)

	db := g.DB(g.Cfg().GetString("custom.db_name"))

	if current_user == userid {
		if tx, err := db.Begin(); err == nil {

			sqlres, _ := tx.Model("t_user").Data(
				gdb.Map{
					"name":         name,
					"email":        email,
					"phone":        phone,
					"phone_notice": phone_notice,
					"email_notice": email_notice,
					"default_page": default_page,
				}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
			if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
				res["code"] = 1
				res["msg"] = "保存成功"
			} else {
				res["code"] = -1
				res["msg"] = "保存失败"
			}

			if res["code"].(int) >= 0 {
				tx.Commit()
			} else {
				tx.Rollback()
			}
		}

	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*user) ChangePwd(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
	}
	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)

	userid := current_user

	params := r.GetFormMap()
	old_pwd := gconv.String(params["old_pwd"])
	new_pwd := gconv.String(params["new_pwd"])

	//old_pwd := r.GetString("old_pwd")
	//new_pwd := r.GetString("new_pwd")

	db := g.DB(g.Cfg().GetString("custom.db_name"))

	count, err := db.GetCount("SELECT * FROM t_user WHERE userid='" + userid + "' AND pwd='" + old_pwd + "'")
	if err == nil && count > 0 {
		sqlres, _ := db.Model("t_user").Data(gdb.Map{"pwd": new_pwd}).Where(fmt.Sprintf("userid='%s'", userid)).Update()
		if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
			res["code"] = 0
			res["msg"] = "保存成功"
		} else {
			res["code"] = -1
			res["msg"] = "保存失败"
		}
	} else {
		res["code"] = -1
		res["msg"] = "旧密码错误"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
